//
//  CommunityMainCellContentController.m
//  ArtDog
//
//  Created by dllo on 16/9/6.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CommunityMainCellContentController.h"
#import "BaseTableView.h"
#import "BaseCollectionView.h"
#import "HLMacro.h"
#import "CommunityTopicTableCell.h"
#import "CommentTableViewCell.h"
#import "ZWYNetTool.h"
#import "NSString+Common.h"
#import "MJRefresh.h"
#import "MJRefreshComponent+RefreshStyle.h"
#import "CommentToolbar.h"
#import "Masonry.h"



// model
#import "CommunityTopicList.h"
#import "CommentList.h"
#import "CommentByLabel.h"
#import "MineMainViewController.h"

@interface CommunityMainCellContentController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, CommentToolbarDelegate>
@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, assign) CGFloat min_y;

@property (nonatomic, strong) CommentByLabel *commentModel;

@property (nonatomic, strong) NSMutableArray<CommentList *> *loadArray;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong) CommentToolbar *toolbar;

@end

@implementation CommunityMainCellContentController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _isOffset = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    [self createTableView];
    [self refreshTableView];
    [self createBottomView];
}

- (void)createBottomView
{
    _toolbar = [[CommentToolbar alloc]init];
    [self.view addSubview:_toolbar];
    _toolbar.backgroundColor = [UIColor whiteColor];
    [_toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(_tableView.mas_bottom).offset(49);
    }];
    _toolbar.delegate = self;
    
    // 键盘
    UIView *freeKBView = [[UIView alloc]init];
    [self.view addSubview:freeKBView];
    [freeKBView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(_toolbar.mas_top);
    }];
    freeKBView.backgroundColor = [UIColor clearColor];
    freeKBView.hidden = YES;
    
    __weak typeof (self) weakSelf = self;
    [self setKeyboard:^(NSNotification *noti, CGFloat height) {
        [weakSelf.toolbar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.tableView.mas_bottom).offset(49 - height);
        }];
        freeKBView.hidden = NO;
        [weakSelf createTapGesture:freeKBView];
        
    } andWillHide:^(NSNotification *noti) {
        [weakSelf.toolbar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.tableView.mas_bottom).offset(49);
        }];
        freeKBView.hidden = YES;
    }];
}

#pragma toolbar 发表评论
- (void)sendCommentFromeButton:(UITextView *)textView andSendButton:(UIButton *)sendBtn
{
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"v3/topic/topicAddCommentImage"] andParams:@{@"imgPaths": @"", @"token": [NSString getUserDefaultToken], @"topicId": [NSString stringWithFormat:@"%@", _topicModel.idField], @"topicType": [NSString stringWithFormat:@"%@", _topicModel.topicType], @"commentText": _toolbar.textView.text}];
    [ZWYNetTool POST:urlString andBody:nil andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/x-www-form-urlencoded", @"Host": @"api.artgoer.cn:8084"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        CommentList *model = [CommentList modelWithDic:result[@"data"]];
        [_loadArray insertObject:model atIndex:0];
        if (_loadArray.count % 10 == 0) {
            [_loadArray removeLastObject];
        }
        [_tableView reloadData];
        _toolbar.textView.text = nil;
        [_toolbar.textView resignFirstResponder];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
}

/** toolbar delegate */
- (void)sendCommentFromeKeyboard:(UITextView *)textView
{
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"v3/topic/topicAddCommentImage"] andParams:@{@"imgPaths": @"", @"token": [NSString getUserDefaultToken], @"topicId": [NSString stringWithFormat:@"%@", _topicModel.idField], @"topicType": [NSString stringWithFormat:@"%@", _topicModel.topicType], @"commentText": _toolbar.textView.text}];
    [ZWYNetTool POST:urlString andBody:nil andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/x-www-form-urlencoded", @"Host": @"api.artgoer.cn:8084"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        CommentList *model = [CommentList modelWithDic:result[@"data"]];
        [_loadArray insertObject:model atIndex:0];
        if (_loadArray.count % 10 == 0) {
            [_loadArray removeLastObject];
        }
        [_tableView reloadData];
        _toolbar.textView.text = nil;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark - 释放键盘手势
- (void)createTapGesture:(UIView *)freeView
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [freeView addGestureRecognizer:tapGesture];
}

- (void)tapAction
{
    [_toolbar.textView resignFirstResponder];
}

#pragma mark - 刷新
- (void)refreshTableView
{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self handleData];
    }];
    [_tableView.mj_header mjRefreshStateHeaderStyle];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageIndex++;
        [self handleLoadData];
    }];
    [_tableView.mj_footer mjRefreshAutoStateFooterStyle];
}

#pragma mark - 数据
- (void)handleData
{
    _pageIndex = 1;
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"v3/topic/topicHomeByLabel"] andParams:@{@"pageIndex": [NSString stringWithFormat:@"%ld", self.pageIndex], @"token": [NSString getUserDefaultToken], @"topicId": [NSString stringWithFormat:@"%@", _topicModel.idField]}];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _loadArray = [NSMutableArray array];
        _commentModel = [CommentByLabel modelWithDic:result[@"data"]];
        for (CommentList *commentModel in _commentModel.commentList) {
            [_loadArray addObject:commentModel];
        }
        [_tableView.mj_header endRefreshing];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
        [_tableView.mj_header endRefreshing];
    }];
}

- (void)handleLoadData
{
    NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"v3/topic/topicHomeByLabel"] andParams:@{@"pageIndex": [NSString stringWithFormat:@"%ld", self.pageIndex], @"token": [NSString getUserDefaultToken], @"topicId": [NSString stringWithFormat:@"%@", _topicModel.idField]}];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        for (NSDictionary *dic in result[@"data"][@"commentList"]) {
            CommentList *commentModel = [CommentList modelWithDic:dic];
            [_loadArray addObject:commentModel];
        }
        [_tableView.mj_footer endRefreshing];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        [_tableView.mj_footer endRefreshing];
        NSLog(@"%@", error);
    }];
}


#pragma mark - tableView
- (void)createTableView
{
    _tableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerNib:[UINib nibWithNibName:@"CommunityTopicTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"communityTopicTableCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentTableViewCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _loadArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        CommunityTopicTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"communityTopicTableCell"];
        if (_commentModel.topic != nil) {
            cell.imageCollectionView.hidden = NO;
            cell.labelCollectionView.hidden = NO;
            cell.topicModel = _commentModel.topic;
            [cell changeCellConfig];
        } else {
            cell.imageCollectionView.hidden = YES;
            cell.labelCollectionView.hidden = YES;
        }
        return cell;
    } else {
        CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentTableViewCell"];
        cell.commentModel = _loadArray[indexPath.row - 1];
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        CGFloat height = [CommunityTopicTableCell getCellHeight];
        NSInteger count = _topicModel.pictures.count;
        if (count == 2) {
            height = height + (SCREEN_WIDTH - 30)/ 2;
        } else if (count == 5 || count == 6) {
            height = height + (SCREEN_WIDTH - 30)/ 3;
        }
        if (_isOffset) {
            _tableView.contentOffset = CGPointMake(0, height);
        }
        return height;
    } else {
        return [CommentTableViewCell getHeight];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (_isOffset == YES) {
        _isOffset = NO;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
